<template>
  <div>
    <el-card class="box-card">
    <!-- 卡片顶部添加品牌按钮 -->
    <el-button type="primary" size="default" icon="Plus" @click="add">添加品牌</el-button>
    <!-- 表格组件：用于显示已有的平台数据
        border：是否显示边框
        label: 表格的列名
        width: 列的宽度
        align: 列的对齐方式
        prop: 字段名称 对应列内容的字段名
    -->
    <el-table style="margin:10px 0px" border :data="brandList">
      <el-table-column prop="id" label="序号" width="80" align="center" type="index"> </el-table-column>
      <!-- table-colum:默认显示数据用div -->
      <el-table-column prop="tmName" label="品牌名称">
        <template #default="scope">
          <span style="color: pink;">{{ scope.row.tmName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="logoUrl" label="品牌logo">
        <template #default="scope">
          <img :src="scope.row.logoUrl" alt="" style="width: 100px; height: 100px;">
        </template>
      </el-table-column>
      <el-table-column prop="desc" label="品牌操作">
        <template #default="scope">
          <el-button type="primary" size="small" icon="Edit" @click="update(scope.row)">修改</el-button>
          <el-popconfirm :title="`您确定要删除${scope.row.tmName}吗？`" width="250px" icon="Delete"
            @confirm="remove(scope.row.id)">
            <template #reference>
              <el-button>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器组件 -->
    <el-pagination @current-change="getBrandList" @size-change="changSize" v-model:current-page="pageNumber"
      v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 100]" :background="true"
      layout="prev, pager, next, jumper, ->, total, sizes" :total="total" />
  </el-card>

  <el-dialog v-model="dialogVisible" :title="addTradeMark.id ? '修改品牌' : '添加品牌'" width="500">
    <el-form style="width: 80%;" :model="addTradeMark" :rules="rules" ref="addFormRef">
      <el-form-item label="品牌名称" label-width="80px" prop="tmName">
        <el-input placeholder="请输入品牌名称" v-model="addTradeMark.tmName"></el-input>
      </el-form-item>
      <el-form-item label="品牌logo" label-width="80px" prop="logoUrl">
        <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
          :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
          <img v-if="addTradeMark.logoUrl" :src="addTradeMark.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 具名插槽 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  </div>

</template>

<script setup lang='ts' name='TradeMark'>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqBrandList, reqAddOrUpdateBrand, reqDeleteBrand } from '@/api/product/trademark';
import type { TradeMark, TradeMarkList, TradeMarkResponseData } from '@/api/product/trademark/type'
import { ElMessage, UploadProps } from 'element-plus';
// 页码
let pageNumber = ref<number>(1);
// 每页显示多少条数据
let pageSize = ref<number>(3);
// 总数
let total = ref<number>(0);
//  获取品牌列表
let brandList = ref<TradeMarkList>([])
// 对话框
let dialogVisible = ref<boolean>(false)
// 表单校验
let addFormRef = ref()

// 收集新增品牌的数据
let addTradeMark = reactive<TradeMark>({
  tmName: '',
  logoUrl: ''
})

//自定义校验规则
// rule: 校验规则对象
// value: 当前输入框的值
// callback: 回调函数，如果校验通过，回调函数的参数为空，如果校验失败，回调函数的参数为错误信息
const validatorLogoUrl = (rule: any, value: string, callback: any) => {
  console.log("进入了上传图片校验： ", rule, value, callback)
  if (value) {
    callback()
  } else {
    callback(new Error('请上传品牌logo'))
  }
};
// 表单校验
const rules = {
  tmName: [
    // required 必填
    // trigger 触发方式 【blur 失去焦点 change 改变】
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  logoUrl: [
    { required: true, validator: validatorLogoUrl }
  ]
}

// 添加品牌
const add = () => {
  dialogVisible.value = true;
  // 清空添加品牌的数据
  addTradeMark.tmName = '';
  addTradeMark.logoUrl = '';
  addTradeMark.id = 0;

  // 方法一：清除之前校验提示 (addFormRef.value有值则调用clearValidate()方法)
  // addFormRef.value?.clearValidate('tmName')
  // addFormRef.value?.clearValidate('logoUrl')
  // 方法二：页面更新后，清除之前校验提示
  nextTick(() => {
    addFormRef.value?.clearValidate('tmName')
    addFormRef.value?.clearValidate('logoUrl')
  })
}
// 修改品牌
const update = (row: TradeMark) => {
  dialogVisible.value = true;

  console.log("修改品牌: ", row);
  Object.assign(addTradeMark, row)
  // addTradeMark.tmName = row.tmName;
  // addTradeMark.logoUrl = row.logoUrl;
  // addTradeMark.id = row.id;

  // 方法二：页面更新后，清除之前校验提示
  nextTick(() => {
    addFormRef.value?.clearValidate('tmName')
    addFormRef.value?.clearValidate('logoUrl')
  })
}
// 添加|修改
const confirm = async () => {
  // 校验之后，再发请求
  await addFormRef.value.validate();

  let result = await reqAddOrUpdateBrand(addTradeMark);
  if (result.code === 200) {
    // 添加成功
    // 1.关闭对话框
    dialogVisible.value = false;
    // 2.提示
    ElMessage.success(addTradeMark.id ? '修改成功' : '添加成功');
    // 3.重新获取品牌列表 (新增在首页，修改还在当前页)
    addTradeMark.id ? pageNumber.value : 1;
    getBrandList();
  } else {
    ElMessage.error(addTradeMark.id ? '修改失败' : '添加失败');
  }
}

// 删除
const remove = async (id: number) => {
  // 删除品牌
  let result = await reqDeleteBrand(id);
  if (result.code === 200) {
    ElMessage.success('删除成功!');
    brandList.value.length > 1? pageNumber.value : pageNumber.value - 1;
    getBrandList();
  }
}

// 上传前校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 上传文件格式png|jpg|gif
  if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
    // 字节 kb Mb
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        message: '上传文件大小不能超过4M',
        type: 'warning'
      })
      return false;
    }
  } else {
    ElMessage({
      message: '上传文件格式不正确',
      type: 'warning'
    })
    return false
  }
};
// 上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // 收集上传图片的url，后续添加到表单中
  addTradeMark.logoUrl = response.data;
  // 图片上传成功,清除掉对应图片的校验错误信息
  addFormRef.value.clearValidate('logoUrl');
}

// 列表 (分页器组件的页码改变事件 )
// 页面点击进来：默认获取第一页的数据
// 点击页码变化时：获取对应页码的数据
// 点击每页条数时：从第一页开始获取数据
const getBrandList = async () => {
  const result: TradeMarkResponseData = await reqBrandList(pageNumber.value, pageSize.value);
  if (result.code === 200) {
    total.value = result.data.total;
    brandList.value = result.data.records;
  }
}
onMounted(() => {
  getBrandList();
})

// 下拉菜单当每页条数变化时，从第一页开始获取数据
const changSize = () => {
  pageNumber.value = 1;
  getBrandList();
}

</script>

<style lang='scss' scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>